package com.bl.student.service.biz.sign.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.enums.PointType;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.dao.model.*;
import com.bl.student.dao.repository.*;
import com.bl.student.service.biz.point.PointService;
import com.bl.student.service.biz.sign.SignService;
import com.bl.student.service.biz.teacher.TeacherService;
import com.bl.student.service.biz.user.UserService;
import com.bl.student.service.vo.sign.UserSignHistoryListVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liangweikang on 18/8/7.
 */
@Service
@Log4j2
public class SignServiceImpl implements SignService{

    private static final String USER_NOT_EXIST = "用户不存在!";
    private static final String DATA_INCORRECT = "数据不正确!";
    private static final String SIGN_INCORRECT = "重复签到!";

    @Autowired
    UserSignRepository userSignRepository;

    @Autowired
    PointService pointService;

    @Autowired
    UserSignHistoryRepository userSignHistoryRepository;

    @Autowired
    PointRepository pointRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    @Autowired
    TeacherRepository teacherRepository;


    @Override
    public void sign(String userId) {
        UserEntity userEntity = userRepository.findOne(userId);
        if (userEntity != null) {
            // 乙方签到
            List<TeacherEntity>  teacherEntityList = teacherRepository.findByMobile(userEntity.getMobile());
            TeacherEntity teacherEntity = ListUtils.getFirst(teacherEntityList);
            UserSignEntity userSignEntity = userSignRepository.findOne(userId);
            UserSignEntity teacherSignEntity = userSignRepository.findOne(teacherEntity.getId());

            int continuitySign;

            if (userSignEntity == null) {
                userSignEntity = new UserSignEntity();
                teacherSignEntity = new UserSignEntity();
                userSignEntity.setUserId(userId);
                Date date = new Date(0);
                userSignEntity.setSignTime(date);
                log.error("date === " + date);

                continuitySign = 0;

            } else {
                continuitySign = userSignEntity.getContinuitySign();
            }

            int point = 0;


            Date signTime = userSignEntity.getSignTime();//获取上次签到时间
            Date nowTime = new Date();//获取当前时间
            Date nowTime1 = new Date();//获取当前时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String signTimeString = formatter.format(signTime) + "  00:00:00";
            SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
            String nowTimeString = formatter2.format(nowTime) + "  00:00:00";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                signTime = sdf.parse(signTimeString);
                nowTime = sdf.parse(nowTimeString);
                log.info(" nowTime ====" + nowTime.toString() + " signTime =====" + signTime.toString());

            } catch (ParseException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }

            //计算间隔时间
            long day = (nowTime.getTime()-signTime.getTime()) / (24*60*60*1000);

            if (day > 1) {
                //签到间隔大于一天，重新计算
                continuitySign = 1;
            } else if (day == 1) {
                //签到天数+1
                continuitySign ++;
            } else {
                //当天重复签到
                log.info("day === " + day + " nowTime ====" + nowTime.toString() + " signTime =====" + signTime.toString());
                throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), SIGN_INCORRECT);
            }

            //计算当前签到分数
            if (continuitySign ==7) {
                PointEntity pointEntity = pointRepository.findByType("SIGN");
                point = pointEntity.getValue();
                //积分相关
                pointService.addPoint(userId, point);
                //积分相关记录
                pointService.addUserPoint(userId, PointType.SIGN , point, "0");
                // 甲方账号增加积分
                pointService.addPointPartyA(teacherEntity.getId(), point);
                // 甲方账号积分相关记录
                pointService.addTeacherPoint(teacherEntity.getId(), PointType.SIGN , point, "0");
                continuitySign = 0;
            }

            //签到
            addUserSign(userSignEntity,continuitySign,nowTime);
            //签到记录
            addUserSignHistory(userId,nowTime,point);

            // 甲方签到
            BeanUtils.copyProperties(userSignEntity, teacherSignEntity);
            teacherSignEntity.setUserId(teacherEntity.getId());
            addUserSign(teacherSignEntity,continuitySign,nowTime);
            //甲方签到记录
            addUserSignHistory(teacherEntity.getId(),nowTime,point);


        } else {
            TeacherEntity teacherEntity = teacherRepository.findOne(userId);
            UserEntity userEntity1 = userService.getUserByMobile(teacherEntity.getMobile());

            UserSignEntity teacherSignEntity = userSignRepository.findOne(userId);
            UserSignEntity userSignEntity = userSignRepository.findOne(userEntity1.getId());
            int continuitySign;

            if (teacherSignEntity == null) {
                teacherSignEntity = new UserSignEntity();
                userSignEntity = new UserSignEntity();
                teacherSignEntity.setUserId(userId);
                Date date = new Date(0);
                teacherSignEntity.setSignTime(date);
                log.error("date === " + date);

                continuitySign = 0;

            } else {
                continuitySign = teacherSignEntity.getContinuitySign();
            }

            int point = 0;


            Date signTime = teacherSignEntity.getSignTime();//获取上次签到时间
            Date nowTime = new Date();//获取当前时间
            Date nowTime1 = new Date();//获取当前时间
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String signTimeString = formatter.format(signTime) + "  00:00:00";
            SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
            String nowTimeString = formatter2.format(nowTime) + "  00:00:00";

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                signTime = sdf.parse(signTimeString);
                nowTime = sdf.parse(nowTimeString);
                log.info(" nowTime ====" + nowTime.toString() + " signTime =====" + signTime.toString());

            } catch (ParseException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }

            //计算间隔时间
            long day = (nowTime.getTime()-signTime.getTime()) / (24*60*60*1000);

            if (day > 1) {
                //签到间隔大于一天，重新计算
                continuitySign = 1;
            } else if (day == 1) {
                //签到天数+1
                continuitySign ++;
            } else {
                //当天重复签到
                log.info("day === " + day + " nowTime ====" + nowTime.toString() + " signTime =====" + signTime.toString());
                throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), SIGN_INCORRECT);
            }

            //计算当前签到分数
            if (continuitySign ==7) {
                PointEntity pointEntity = pointRepository.findByType("SIGN");
                point = pointEntity.getValue();
                // 甲方积分相关
                pointService.addPointPartyA(userId, point);
                // 甲方积分相关记录
                pointService.addTeacherPoint(userId, PointType.SIGN , point, "0");
                // 乙方账号增加积分
                pointService.addPoint(userEntity1.getId(), point);
                // 乙方账号积分相关记录
                pointService.addUserPoint(userEntity1.getId(), PointType.SIGN , point, "0");
                continuitySign = 0;
            }

            // 甲方签到
            addUserSign(teacherSignEntity,continuitySign,nowTime);
            // 甲方签到记录
            addUserSignHistory(userId,nowTime,point);

            // 乙方签到
            BeanUtils.copyProperties(teacherSignEntity, userSignEntity);
            userSignEntity.setUserId(userEntity1.getId());
            addUserSign(userSignEntity,continuitySign,nowTime);
            // 乙方签到记录
            addUserSignHistory(userEntity1.getId(),nowTime,point);
        }

    }

    @Override
    public UserSignHistoryListVo getList(String userId) {

        UserSignHistoryListVo userSignHistoryListVo = new UserSignHistoryListVo();
        List<UserSignHistoryEntity> userSignHistoryEntityList = new ArrayList<>();
        userSignHistoryEntityList = userSignHistoryRepository.findByUserId(userId);
        userSignHistoryListVo.setTotalCount(userSignHistoryEntityList.size());
        userSignHistoryListVo.setList(userSignHistoryEntityList);

        return userSignHistoryListVo;
    }

    @Override
    public UserSignEntity getUserSign(String userId) {
        UserSignEntity userSignEntity = userSignRepository.findOne(userId);
        return userSignEntity;
    }

    private void addUserSignHistory(String userId, Date nowTime, int point) {
        UserSignHistoryEntity userSignHistoryEntity = new UserSignHistoryEntity();
        userSignHistoryEntity.setPoint(point);
        userSignHistoryEntity.setUpdateTime(new Date());
        userSignHistoryEntity.setCreateTime(new Date());
        userSignHistoryEntity.setSignTime(nowTime);
        userSignHistoryEntity.setUserId(userId);
        userSignHistoryEntity.setId(UUIDUtils.getUUID());
        userSignHistoryRepository.save(userSignHistoryEntity);
    }

    private void addUserSign(UserSignEntity userSignEntity,int continuitySign, Date nowTime) {
        userSignEntity.setUpdateTime(new Date());
        userSignEntity.setCreateTime(new Date());
        userSignEntity.setContinuitySign(continuitySign);
        userSignEntity.setSignTime(nowTime);
        userSignRepository.save(userSignEntity);
    }


}
